package edu.gatech.cs2340.tigershroud;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

	/**
	 * The TigerShroudActivity starts the application and asks the user to login
	 * @author []
	 * @version 9.0x, Build April 3, 2012.
	 */
public class TigerShroud2Activity extends Activity 
{
	private UserDataSource ds;
	private MasterControlClass mcc;
	private Button login, register, fpassw, funame, submit, close, recover;;
	private EditText user, pass, etadj1, etemail, etansw;; 
	private TextView logstat, tvques, adj1, adj2, adj3;;
	private String uname, passw, sadj1, semail, sansw, type;;
	private User temp;
	private List<User> ul;
	private Dialog dialog;
	
	/**
	 * The onCreate method is a default android method that is called when the
	 * activity is first started. This onCreate method assigns passed objects to variables, 
	 * opens the database, determines the layout of
	 * the activity, and sets listeners for items within the activity.
	 * @param saveInstanceState the Bundle name value pair that represents the state of the object
	 *
	 */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mcc = new MasterControlClass();
        ds = new UserDataSource(this);
        ds.open();
        ds.insertSuperUser();
        
        login = (Button) findViewById(R.id.blogin);
        register = (Button) findViewById(R.id.bregister);
        fpassw = (Button) findViewById(R.id.bfpassw);
        funame = (Button) findViewById(R.id.bfuname);
        
        fpassw.setOnClickListener(new View.OnClickListener() 
        {
        	public void onClick(View v) 
        	{
        	   popup("Password Recovery", "Username:", "Password: ", "passw");
        	}
        });
        
        funame.setOnClickListener(new View.OnClickListener() 
        {
        	public void onClick(View v) 
        	{
        		popup("Username Recovery", "Password:", "Username: ", "uname");
        	}
        });
	
        login.setOnClickListener(new View.OnClickListener() 
        {
	        public void onClick(View v) 
	        {	
	        	logstat = (TextView)findViewById(R.id.tvlogin);
	        	user = (EditText)findViewById(R.id.etuname);
	        	uname = user.getText().toString();
	        	pass = (EditText)findViewById(R.id.etpass);
	        	passw = pass.getText().toString();
	        	
	        	User user = new User();
	        	user = ds.findUser(uname);

	        	if(user != null)
	        	{	        		
	        		Log.d("LOGIN", "username entered: " + uname);
	        		Log.d("LOGIN", "password entered: " + passw);
	        		Log.d("LOGIN", "username from user object: " + user.getUserName());
	        		Log.d("LOGIN", "password from user object: " + user.getPass());
	        		
	        		if(passw.equals(user.getPass()))
	        		{	        	
	        			logstat.setText("Login succeeded!");
	        			mcc.setUname(uname);
	        			
		        		if(validateType(uname))
		        		{
		        			mcc.setUtype("super");
		        		}
		        		else
		        		{
		        			mcc.setUtype("normal");
		        		}
	        			
		        		Log.d("LOGIN", "type: " + mcc.getUtype());
	        			Intent intent = new Intent(TigerShroud2Activity.this, TodoListActivity.class);
	        			intent.putExtra("uname", mcc.getUname());
	        			intent.putExtra("utype", mcc.getUtype());
	        			
	        			ds.close();
	        			Toast.makeText(TigerShroud2Activity.this, "Successful login...", Toast.LENGTH_LONG).show();
	        			startActivity(intent);
	        		} 
	        		else 
	        		{
	        			logstat.setText("Login failed! Incorrect username or password.");
	        			Toast.makeText(TigerShroud2Activity.this, "Please try again...", Toast.LENGTH_LONG).show();
	        			Log.d("LOGIN", "user not null, wrong password");
	        		}
	        	} 
	        	else 
	        	{
        			logstat.setText("Login failed! Incorrect username or password.");
        			Toast.makeText(TigerShroud2Activity.this, "Please try again...", Toast.LENGTH_LONG).show();
        			Log.d("LOGIN", "user is null, no such user");
        		}
	        }
        });
        
        register.setOnClickListener(new View.OnClickListener() 
        {
        	 /**
	    	 * This method inside the anonymous inner-class OnClickListener
	    	 * determines the behavior of the application when the item is clicked.
	    	 * When the item is clicked, the user is taken to another activity that
	    	 * lets the user create a task.
	    	 * @param view the View that is generated by the parent activity
	    	 */
        	public void onClick(View v) 
        	{
        		ds.close();
	        	Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
                startActivity(intent);
        	}
        });
    }
    
    /**
	 * Determines the behavior of the activity once it resumes
	 * When the activity resumes, opens the database.
	 */
    protected void onResume()
    {
    	super.onResume();
    	ds.open();
    }
    
    public void popup(String title, String a1, String a2, String t)
    {
    	dialog = new Dialog(TigerShroud2Activity.this);
        dialog.setContentView(R.layout.recovery);
        dialog.setTitle(title);
        dialog.setCancelable(true);
 
        etadj1 = (EditText) dialog.findViewById(R.id.etadj1);
        etemail = (EditText) dialog.findViewById(R.id.etemail);
        etansw = (EditText) dialog.findViewById(R.id.etansw);
        
        tvques = (TextView) dialog.findViewById(R.id.tvques);
	  	adj1 = (TextView) dialog.findViewById(R.id.tvadj1);
	  	adj2 = (TextView) dialog.findViewById(R.id.tvadj2);
        adj3 = (TextView) dialog.findViewById(R.id.tvadj3);
	   
	  	adj1.setText(a1);
	  	adj2.setText(a2);
	  	
        type = t;
       
        submit = (Button) dialog.findViewById(R.id.bsubmit);
        close = (Button) dialog.findViewById(R.id.bclose);
        recover = (Button) dialog.findViewById(R.id.brecover);
        
        temp = null;
        ul = null;
         
        submit.setOnClickListener(new View.OnClickListener() 
        {
        	public void onClick(View v) 
         	{
                sadj1 = etadj1.getText().toString();
                semail = etemail.getText().toString();
                sansw = etansw.getText().toString();
                
         		if(validateUsername(sadj1) && validateEmail(semail))
         		{
         			if(type.equals("passw"))
         			{
         				Log.d("LOGIN", "doing password recovery");
	         			temp = ds.findUser(sadj1);
	         			if(temp != null && temp.getEmail().equals(semail))
	         			{
	         				tvques.setText(temp.getQuestion());
	         			}
	         			else
	         			{
	             			Toast.makeText(getApplicationContext(), 
	                     			"Validation failed, bad credentials detected, please try again..."
	             					, Toast.LENGTH_LONG).show();
	         			}
         			}
         			else if(type.equals("uname"))
         			{
         				Log.d("LOGIN", "doing username recovery");
	         			ul = ds.usernameRecovery(semail, sadj1);
	         			temp = ul.get(0);
	         			if(ul != null && ul.size() > 0 && validateEmail(temp.getEmail()))
	         			{
	         				tvques.setText(temp.getQuestion());
	         			}
	         			else
	         			{
	             			Toast.makeText(getApplicationContext(), 
	                     			"Validation failed, bad credentials detected, please try again..."
	             					, Toast.LENGTH_LONG).show();
	         			}
         			}
         		}
         	}
         });
         
         close.setOnClickListener(new View.OnClickListener() 
         {
         	public void onClick(View v) 
         	{
         		dialog.dismiss();
         	}
         });
         
         recover.setOnClickListener(new View.OnClickListener() 
         {
         	public void onClick(View v) 
         	{
            	sansw = etansw.getText().toString();
            	
         		if(type.equals("passw"))
         		{
             		if(validateUsername(sadj1) && validateEmail(semail) 
             				&& validateAnswer(sansw) && temp != null && sansw.equals(temp.getAnswer()) 
             				&& semail.equals(temp.getEmail()))
             		{
             			adj3.setText(temp.getPass());
             		}
             		else
             		{
             			Toast.makeText(getApplicationContext(), 
                     			"Validation failed, bad credentials detected, please try again..."
             					, Toast.LENGTH_LONG).show();
             		}
         		}
         		else if(type.equals("uname"))
         		{
         			if(validateUsername(sadj1) && validateEmail(semail) 
         					&& validateAnswer(sansw) && temp != null && sansw.equals(temp.getAnswer()) 
         					&& ul != null && semail.equals(temp.getEmail()))
         			{
         				adj3.setText(temp.getUserName());
         			}
         			else
         			{
         				Toast.makeText(getApplicationContext(), 
                     			"Validation failed, bad credentials detected, please try again..."
             					, Toast.LENGTH_LONG).show();
         			}
         		}
         	}
         });
        
         dialog.show();
 	}
    
    public boolean validateType(String uname)
    {
    	if(ds != null)
    	{
	    	User temp = ds.findUser(uname);
	    	if(temp.getType().equals("super"))
	    	{
	    		return true;
	    	}
    	}
    	return false;
    }
    
    public boolean validateEmail(String email)
    {
    	if(emptyInputValidation(email, "an email"))
    	{
        	if(email.indexOf('@') == -1)
        	{
        		Toast.makeText(getApplicationContext(), 
            			"Email validation failed, please enter a valid email address...", Toast.LENGTH_LONG).show();
        		return false;
        	}
        	return true;
    	}
    	return false;
    }
    
    public boolean validateUsername(String uname)
    {
    	return emptyInputValidation(uname, "a username");
    }
    
    public boolean validatePassword(String passw)
    {
    	return emptyInputValidation(passw, "a password");
    }

    public boolean validateAnswer(String answer)
    {
    	return emptyInputValidation(answer, "an answer to the security question");
    }
    
    public boolean emptyInputValidation(String d, String e)
    {
    	if(d.equals(""))
    	{
    		Toast.makeText(getApplicationContext(), 
        			"Please enter " + e + "...", Toast.LENGTH_LONG).show();
    		return false;
    	}
    	return true;
    }
}